package com.feilong.edgeAI.service;


import android.app.Service;
import android.content.Intent;
import android.os.Environment;
import android.os.IBinder;
import android.util.Log;

import com.feilong.mscv5plus.MessageClient;

import org.greenrobot.eventbus.EventBus;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
/**
 * Created by【仿脑科技】
 *
 * @Author: potato
 * @CreateDate: 2024/3/19 14:57
 */
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.Socket;

/**
 * 更新理解引擎的tcp
 */
public class TCPFileClient {
    private static final String TAG = "TCPFileClient";
    public static final String FILE_SERVER_IP = "127.0.0.1";
//    public static final String FILE_SERVER_IP = "192.168.3.28";
    public static final int FILE_SERVER_PORT = 9527;
    public  Socket socket;
    public  void startClient(OnSendFileCompleteListener listener){
        Log.d(TAG, "startClient:socket= "+socket);
        if (socket == null) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Log.i(TAG, "启动客户端");
                        socket = new Socket(FILE_SERVER_IP, FILE_SERVER_PORT);
                        Log.i(TAG, "客户端连接成功");
                        PrintWriter pw = new PrintWriter(socket.getOutputStream());

                        InputStream inputStream = socket.getInputStream();

                        byte[] buffer = new byte[1024];
                        int len = -1;
                        while ((len = inputStream.read(buffer)) != -1) {
                            String data = new String(buffer, 0, len);
                            if(null!=listener&&"success".equals(data)){
                                listener.onSendFileComplete();
                            }
                            Log.i(TAG, "收到服务器file的数据---------------------------------------------:" + data);
                        }
                        Log.i(TAG, "客户端断开连接");
                        pw.close();

                    } catch (Exception EE) {
                        EE.printStackTrace();
                        Log.e(TAG, "run: "+EE.getMessage());
                        Log.i(TAG, "客户端无法连接服务器");

                    }finally {
                        try {
                            if(null!=socket){
//                                socket.close();

                                socket = null;
                            }
                            Log.d(TAG, "run: socket.close()");
                        } catch (Exception e) {
                            Log.e(TAG, "run: "+e.getMessage());
                            e.printStackTrace();
                        }
                    }
                }
            }).start();
        }
    }
    public void sendTcpFile(final String filePath ){
        Log.d(TAG, "sendTcpMessage: "+filePath);
        if (socket != null && socket.isConnected()) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try{
                        FileInputStream fis = new FileInputStream(filePath);
                        DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
                        byte[] buffer = new byte[1024]; // 缓冲区大小可根据实际情况调整
                        int count;
                        Log.d(TAG, "doInBackground: ");
                        // 发送文件大小
//                        dos.writeInt((int) fis.getChannel().size()); // 注意，这里假设文件大小不超过Integer.MAX_VALUE
                        // 发送文件内容
                        while ((count = fis.read(buffer)) > 0) {
                            dos.write(buffer, 0, count);
                            Log.d(TAG, "doInBackground: count"+count);
                        }
                        Log.d(TAG, "run: ><>>>");
                        dos.writeBytes("EOF");
                        dos.flush();
                    } catch (Exception e) {
                        Log.d(TAG, "sendTcpFile run: "+e.getMessage());
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }

    public void sendTcpMessage(final String msg){
        Log.d(TAG, "sendTcpMessage: "+msg);
        if (socket != null && socket.isConnected()) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        socket.getOutputStream().write(msg.getBytes());
                        socket.getOutputStream().flush();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }else{
            if(msg.contains("ifly_ID")){
                return;
            }
            EventBus.getDefault().post(new MessageClient("error"));
            Log.d(TAG, "sendTcpMessage: error");
        }
    }

    public interface OnSendFileCompleteListener {
        void onSendFileComplete();
        void onSendFileFailure();
    }
}